//
// Created by wty on 22-7-19.
//
#include"sylar/tcp_server.h"
#include"sylar/iomanager.h"
#include"sylar/log.h"
#include"sylar/bytearray.h"
#include"sylar/address.h"

sylar::Logger::ptr logger = SYLAR_LOG_ROOT();

class EchoServer:public sylar::TcpServer{
public:
    // 服务器协议启动  文本或者二进制
    EchoServer(int type);
    void handleClient(sylar::Socket::ptr client);
private:
    int m_type;
};

EchoServer::EchoServer(int type):m_type(type){

}

void EchoServer::handleClient(sylar::Socket::ptr client){
    SYLAR_LOG_INFO(logger)<<"handle client "<<*client;
    sylar::ByteArray::ptr ba(new sylar::ByteArray);
    std::vector<iovec> iov_all;
    while(true){
        ba->clear();
        std::vector<iovec> iovs;      
        ba->getWriteBuffers(iovs, 4);  // buffersize影响缓冲区格式，1024可能会输出完整的
        int rt = client->recv(&iovs[0], 1);  // iov链表的长度只是1

        iovs[0].iov_len = rt;
        iov_all.push_back(iovs[0]);

        SYLAR_LOG_INFO(logger)<<" iovs size "<< iovs.size();
        if(rt==0){
            SYLAR_LOG_INFO(logger)<<" client close "<< *client;
            break;
        }else if(rt<0){
            SYLAR_LOG_INFO(logger)<<" client error rt "<< rt
                                << "error="<<errno<<" errstr="<<strerror(errno);
            break;
        }
        std::cout<<std::endl;
        ba->setPosition(ba->getPosition()+rt);
        ba->setPosition(0);    // 读取的时候从m_position=0
        if(m_type==1){ 
            SYLAR_LOG_INFO(logger) << ba->toString();
        }

    }

}

int type = 1; //输出文本形式

void run(){
    EchoServer::ptr es(new EchoServer(type));
    auto addr = sylar::Address::LookupAny("0.0.0.0:8000");
    while(!es->bind(addr)){
        sleep(1);
    }
    es->start();
}

int main(int argc, char**argv){
    sylar::IOManager iom(2);
    iom.schedule(run);
    return 0;
}